package org.example.cloudapply.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.transaction.Transactional;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.example.cloudapply.config.WechatConfig;
import org.example.cloudapply.dto.HandleApplicationDTO;
import org.example.cloudapply.dto.PageDTO;
import org.example.cloudapply.entity.Application;
import org.example.cloudapply.entity.ApplicationStatus;
import org.example.cloudapply.repository.ApplicationRepository;

import org.example.cloudapply.repository.ScheduleJobRepository;
import org.example.cloudapply.vo.AdminApplicationVO;
import org.example.cloudapply.vo.AdminProcessedVO;
import org.example.cloudapply.vo.ApplicationDetailVO;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Service
@Validated
public class AdminApplicationService {

    private final ApplicationRepository applicationRepository;
    private final ScheduleJobRepository scheduleJobRepository;
    private final WechatService wechatService;
    private final WechatConfig wechatConfig;
    public AdminApplicationService(ApplicationRepository applicationRepository, ScheduleJobRepository scheduleJobRepository, WechatService wechatService, WechatConfig wechatConfig) {
        this.applicationRepository = applicationRepository;
        this.scheduleJobRepository = scheduleJobRepository;
        this.wechatService = wechatService;
        this.wechatConfig = wechatConfig;
    }
    //得到等待处理的方法
    public PageInfo<AdminApplicationVO> getPendingApplications(PageDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<Map<String, Object>> list = applicationRepository.findPendingApplications();
        List<AdminApplicationVO> voList = list.stream().map(map -> {
            AdminApplicationVO vo = new AdminApplicationVO();
            vo.setApplyId((Integer) map.get("apply_id"));
            vo.setName((String) map.get("name"));
            vo.setRole((String) map.get("role"));
            vo.setSchoolId((String) map.get("school_id"));
            vo.setEmail((String) map.get("email"));
            vo.setPhone((String) map.get("phone"));
            vo.setCpuCores((Integer) map.get("cpu_cores"));
            vo.setMemoryGb((Integer) map.get("memory_gb"));
            vo.setGpuSupported((Boolean) map.get("gpu_supported"));
            vo.setGpuEnabled((Boolean) map.get("gpu_enabled"));
            vo.setCloudType((String) map.get("cloud_type"));
            vo.setApplyTime((LocalDateTime) map.get("apply_time"));
            vo.setDurationDays((Integer) map.get("duration_days"));
            return vo;
        }).collect(Collectors.toList());

        return new PageInfo<>(voList);
    }

    //改变申请的状态
    public void handleApplication(@Valid HandleApplicationDTO dto) {
        Application application = new Application();
        application.setApplyId(dto.getApplyId());
        ApplicationDetailVO detailVO = new ApplicationDetailVO();
        detailVO=applicationRepository.findDetailById(dto.getApplyId());

        if (dto.getIsApprove()) {
            application.setStatus(ApplicationStatus.approved);
            application.setAccountInfo(dto.getAccountInfo());
            //通过后发送消息
            sendApprovalNotification(detailVO);

        } else {
            application.setStatus(ApplicationStatus.rejected);
            application.setRejectReason(dto.getRejectReason());
            scheduleJobRepository.deleteByApplyId(dto.getApplyId());
            sendRejectNotification(detailVO, dto.getRejectReason());
        }

        int affected = applicationRepository.updateApplicationStatus(application);
        if (affected == 0) {
            throw new RuntimeException("申请不存在或状态已变更");
        }
    }
    //得到申请处理后的申请
    public PageInfo<AdminProcessedVO> getProcessedApplications(int page, int size) {
        PageHelper.startPage(page, size);
        List<Map<String, Object>> list = applicationRepository.findProcessedApplications();
        List<AdminProcessedVO> voList = list.stream().map(map -> {
            AdminProcessedVO vo = new AdminProcessedVO();
            vo.setApplyId((Integer) map.get("apply_id"));
            vo.setName((String) map.get("name"));
            vo.setRole((String) map.get("role"));
            vo.setSchoolId((String) map.get("school_id"));
            vo.setEmail((String) map.get("email"));
            vo.setPhone((String) map.get("phone"));
            vo.setCpuCores((Integer) map.get("cpu_cores"));
            vo.setMemoryGb((Integer) map.get("memory_gb"));
            vo.setGpuSupported((Boolean) map.get("gpu_supported"));
            vo.setGpuEnabled((Boolean) map.get("gpu_enabled"));
            vo.setCloudType((String) map.get("cloud_type"));
            vo.setApplyTime((LocalDateTime) map.get("apply_time"));
            vo.setStatus((String) map.get("status"));
            vo.setDurationDays((Integer) map.get("duration_days"));
            return vo;
        }).collect(Collectors.toList());

        return new PageInfo<>(voList);
    }
    //删除已经处理的申请
    @Transactional
    public void deleteProcessedApplication(Integer applyId) {
        scheduleJobRepository.deleteByApplyId(applyId);
        int affected = applicationRepository.logicalDelete(applyId);
        if (affected == 0) {
            throw new RuntimeException("申请不存在或已被删除");
        }
    }

    //发送申请通过的消息的模板
    @Async
    public void sendApprovalNotification(ApplicationDetailVO detail) {
        try {
            Map<String, String> content = new HashMap<>();
            content.put("thing1", "云资源申请通过");  // 对应模板中的第一个参数
            content.put("thing11", String.format("%s %d核%dG%s",
                    detail.getCloudType(),
                    detail.getCpuCores(),
                    detail.getMemoryGb(),
                    detail.getGpuEnabled() ? "+GPU" : ""
                    )
            );
            content.put("time10", detail.getExpireTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));

            wechatService.sendSubscribeMessage(
                    detail.getOpenid(),
                    wechatConfig.getApprovalTemplateId(),
                    content
            );
        } catch (Exception e) {
            log.error("微信通知发送失败，申请ID：{}，错误：{}", detail.getApplyId(), e.getMessage());
        }
    }

    @Async
    public void sendRejectNotification(ApplicationDetailVO detail, String reason) {
        try {
            Map<String, String> content = new HashMap<>();
            content.put("thing2", "云资源申请未通过");
            content.put("thing5", String.format("%s申请被拒绝", detail.getCloudType()));
            content.put("thing3", reason); // 拒绝原因

            wechatService.sendSubscribeMessage(
                    detail.getOpenid(),
                    wechatConfig.getRejectTemplateId(),
                    content
            );
        } catch (Exception e) {
            log.error("拒绝通知发送失败，申请ID：{}", detail.getApplyId(), e);
        }
    }
}
